package com.juyu.miliao.api.service;

import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.mysql.VipPayDao;
import com.juyu.miliao.api.domain.BillDetail;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.api.domain.VipPay;
import com.juyu.miliao.api.exception.WrongNoDepositException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class VipPayService {
    @Resource
    private VipPayDao vipPayDao;
    @Resource
    private UserWalletDao userWalletDao;

    @Resource
    private BillDetailDao billDetailDao;
    @Resource
    private AppKeyService appkeyService;

    public List<VipPay> getVipPayByUserId(long userId, long hostUserId, int type) {
        return vipPayDao.getVipPayByUserId(userId, hostUserId, type);
    }


    /**
     * 聊天时赠送金币红包
     */
    @Transactional(rollbackFor = Exception.class)
    public void payContact(long userId, long hostUserId, int type) {
        // 获取用户钱包
        UserWallet userWallet = userWalletDao.getUserWalletById(userId);
        // 判断钱包金币是否够用
        if (380 > userWallet.getDeposit()) {
            throw new WrongNoDepositException("金币不足");
        } else {
            userWallet.setDeposit(380);
            userWalletDao.minusDeposit(userWallet);
            VipPay vipPay = new VipPay();
            vipPay.setBuyUserId(userId);
            vipPay.setHostUserId(hostUserId);
            if (type == 1) {
                vipPay.setContact(appkeyService.getAppKeyByKey("vest_tcyl_qq").getValue());

            } else {
                vipPay.setContact(appkeyService.getAppKeyByKey("vest_tcyl_wx").getValue());
            }
            vipPay.setBuyType(type);
            vipPayDao.insertVipPay(vipPay);

            //添加明细
            BillDetail billDetail = new BillDetail();
            billDetail.setRecordType(type == 1 ? 11 : 12);
            billDetail.setInUserId(-1L);
            billDetail.setOutUserId(userId);
            billDetail.setDiamond(0);
            billDetail.setSpend(380);
            billDetailDao.insertBillDetail(billDetail);
        }
    }
}
